package loadsave.loadsaveobject;

import java.util.*;

import loadsave.Saver;

public class LoadSaveObjectComposite extends LoadSaveComposite {
	private Map<String, LoadSaveObject> values;
	
	public LoadSaveObjectComposite(String name, String type) {
		super(name, type);
		values = new HashMap<String, LoadSaveObject>();
	}
	
	@Override
	public Iterator<LoadSaveObject> getIterator() {
		return new Iterator<LoadSaveObject>() {
			java.util.Iterator<String> iter;
			LoadSaveObject currKey, currVal;
			boolean nextExists = true;
			 
			@Override
			public void init() {
				iter = values.keySet().iterator();
				next();
			}

			@Override
			public boolean hasNext() {
				return nextExists;
			}

			@Override
			public void next() {
				if (iter.hasNext()) {
					currKey = new LoadSavePrimitive("id", "String", iter.next());
					currVal = values.get(currKey.getValue());
				}
				else
					nextExists = false;
			}

			@Override
			public LoadSaveObject getCurrKey() {
				return currKey;
			}

			@Override
			public LoadSaveObject getCurrVal() {
				return currVal;
			}
			
		};
	}

	public void add(String id, LoadSaveObject value) {
		value.setName(id);
		values.put(id, value);
	}
	
	@Override
	public LoadSaveObject get(String id) {
		return values.get(id);
	}

	@Override
	public void save(Saver s) {
		s.saveLoadSaveObjectComposite(this);
	}

	@Override
	public String toString() {
		StringBuilder toReturn = new StringBuilder();
		toReturn.append("LoadSaveObjectComposite: ");
		toReturn.append(getName());
		toReturn.append(':');
		toReturn.append(getType());
		toReturn.append(" = {\n");
		Iterator<LoadSaveObject> i = getIterator();
		for (i.init(); i.hasNext(); i.next()) {
			toReturn.append(i.getCurrVal().toString());
		}
		toReturn.append("}\n");
		return toReturn.toString();
	}

}
